import {
    getUserListApi,
    getUserDetailApi,
    getDeptTreeApi,
    changeUserStatusApi,
    insetUserApi,
    updateUserApi,
    exportUserListApi,
    importUserListApi,
    downloadUserTemplateApi,
    DeptTreeInfo, UserDetailProps,
} from '@/api/system/user';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import FormConfig from './form-config.json';
import {message, Tree} from 'antd';
import {publicDealTree, publicFilterEmptyField, publicFormatTime} from '@/utils';
import useRenderCom from '@/hooks/useRenderCom';
import {ComponentMethods} from '@/types/app.ts';
import {Modal} from "antd";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import style from "@/pages/System/Menu/index.module.scss";
import {DynamicFormRef} from "@/types/form";

interface UserDataType {
    userId: number;
    userName: string;
    sex: string;
    postIds: number[];
    roleIds: number[];
    status: boolean;
}

const SystemUser = () => {
    const {
        renderForm,
        renderTable,
        getFormValue,
        resetFormValue,
        renderDialog,
        setFormSchema,
        checkFormRequire
    } = useRenderCom();
    const deptTrees = useRef<DeptTreeInfo[]>([]);
    const [pageSize, setPageSize] = useState(30);
    const [pageNum, setPageNum] = useState(1);
    const [total, setTotal] = useState(0);
    const [treeLoading, setTreeLoading] = useState(false);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [currentNode, setCurrentNode] = useState<DeptTreeInfo>({});
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [tableData, setTableData] = useState<UserDataType[]>([]);
    const [loading, setLoading] = useState(false);
    const currentNodeRef = useRef(currentNode);
    const modalFormRef: any = useRef<DynamicFormRef>(null);
    const queryListRef = useRef({
        current: 1,
        size: 30
    })
    const formRef: any = useRef(null);
    const getTableData = useCallback(() => {
        if (!currentNodeRef.current.key) return;
        setLoading(true);
        const formList = getFormValue(formRef.current);
        const params: any = {
            ...formList,
            pageNum: queryListRef.current.current,
            pageSize: queryListRef.current.size,
            deptId: currentNodeRef.current.key,
        }
        if (formList.createTimes && formList.createTimes.length) {
            params["startTime"] = publicFormatTime(formList.createTimes[0], "yyyy-MM-dd");
            params["endTime"] = publicFormatTime(formList.createTimes[1], "yyyy-MM-dd");
            delete params.createTimes
        }
        getUserListApi(publicFilterEmptyField(params))
            .then((result) => {
                if (result?.rows) {
                    const newData = result.rows.map((ele: any) => ({
                        ...ele,
                        key: ele.userId,
                        status: ele.status === "0"
                    }));
                    setTableData(newData);
                } else {
                    setTableData([]);
                }
                setTotal(result.total || 0);
            })
            .finally(() => {
                setLoading(false);
            });
    }, [pageSize, pageNum]);
    useEffect(() => {
        let isMounted = true;
        const fetchData = async () => {
            if (treeLoading) return;
            setTreeLoading(true);
            try {
                const res = await getDeptTreeApi();
                if (isMounted) {
                    const deptTreeData = publicDealTree(res);
                    deptTrees.current = deptTreeData;
                    if (!currentNode.key && deptTreeData.length) {
                        currentNodeRef.current = deptTreeData[0];
                        setSelectedKeys([deptTreeData[0].key]);
                        setCurrentNode(deptTreeData[0]);
                        getTableData();
                    }
                }
            } finally {
                if (isMounted) {
                    setTreeLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false;
        };
    }, []);
    const handleTable = async (item?: UserDataType) => {
        const isEdit = item && item.userId;
        let userInfo: UserDetailProps;
        if (isEdit && item) {
            userInfo = await getUserDetailApi(item?.userId);
            item.postIds = userInfo.postIds;
            item.roleIds = userInfo.roleIds;
        }
        renderDialog({
            title: `${isEdit ? "编辑" : "新增"}用户`,
            content: renderForm({
                ref: modalFormRef,
                formId: 'dialogForm',
                schema: FormConfig.DialogSchema as any,
                handlers: handlers,
                formList: isEdit ? {...item, status: item?.status ? "0" : "1"} : {userType: "1", status: "0"},
            }),
            onOk: (cb: () => void) => {
                const api = isEdit ? updateUserApi : insetUserApi;
                checkFormRequire(modalFormRef.current).then((values) => {
                    const params: any = {...values};
                    if (isEdit) {
                        params["userId"] = item?.userId
                        params["userName"] = item?.userName
                    }
                    api(params).then((res) => {
                        message.success(`${isEdit ? "编辑" : "新增"}用户成功`);
                        getTableData();
                        cb && cb();
                    })
                })
            }
        })
        setTimeout(() => {
            setFormSchema(modalFormRef.current, [
                {
                    field: 'deptId',
                    path: 'componentProps.treeData',
                    value: deptTrees.current,
                }
            ]);
        })
    }
    const onHandleButtonGroup = (options: any) => {
        const {item, row, value} = options;
        const obj: any = {
            search: () => {
                getTableData();
            },
            refresh: () => {
                resetFormValue(formRef.current);
                getTableData();
            },
            insertRow: () => handleTable(),
            editRow: () => handleTable(row),
            tableChange: () => {
                queryListRef.current = {
                    current: value.current,
                    size: value.pageSize
                }
                getTableData();
            }
        };
        obj[item.field] && obj[item.field]();
    };
    const onHandleClickStatus = (options: any) => {
        const {value, item, record, event} = options;
        Modal.confirm({
            title: "提示",
            icon: <ExclamationCircleOutlined/>,
            content: `确认${value ? "启用" : "停用"}用户【${record.userName}】?`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                changeUserStatusApi({
                    status: value ? "0" : "1",
                    userId: record.userId
                }).then(() => {
                    message.success(`${value ? "启用" : "停用"}用户【${record.userName}】成功`);
                    getTableData();
                })
            },
            onCancel: () => {
                getTableData();
            }
        })
        event.nativeEvent.stopPropagation();
    }
    const handlers: ComponentMethods = {
        handleClickStatus: (options: any) => onHandleClickStatus(options),
        handleUserChange: (options: any) => {
        },
        handleButtonGroup: (options: any) => onHandleButtonGroup(options.value),
        handleTableClick: ({value}) => onHandleButtonGroup(value),
        handleTableChange: (options) => onHandleButtonGroup(options)
    };
    return (
        <div className={'w-full h-full flex'}>
            <div className={'w-[150px] h-full'}>
                <Tree
                    selectedKeys={selectedKeys}
                    autoExpandParent={autoExpandParent}
                    treeData={deptTrees.current as any}
                />
            </div>
            <div className={'w-[calc(100%_-_150px)] h-full flex flex-col'}>
                <div className={'w-full'}>
                    {renderForm({
                        ref: formRef,
                        formId: 'filterForm',
                        schema: FormConfig.FilterSchema,
                        handlers: handlers,
                        formList: {},
                    })}
                </div>
                <div className={"flex-1 min-h-0 overflow-hidden"}>
                    {renderTable<UserDataType>({
                        tableHeader: FormConfig.TableHeader as any,
                        tableData: tableData,
                        handlers: handlers,
                        isLoading: loading,
                        queryList: queryListRef.current,
                        total: total,
                    })}
                </div>
            </div>
        </div>
    );
};
export default SystemUser;
